<?php

require_once('base.php');
require_once('page.php');
require_once('../model/user.php');
require_once('../model/file.php');

/**
 * This class provides the link to download a page or set of pages.
 */
class folio_PageArchiveLink extends folio_BaseView {

    function __construct( $page = -1, $tag = '') {
        $url = url;
        if( $page == -1 )
            $oTitle = __gettext('Download an archive of all these pages');
        else
            $oTitle = __gettext('Download this page');

        $this->html = <<< END
<a href={$url}mod/folio/ajax/PageArchive.php?page={$page}&tag={$tag}>{$oTitle}</a>
END;
    }
}

/**
 * This class will return the archived page(s) requested.
 */
class folio_PageArchiveZip extends folio_BaseView {

    private $zip;
    private $filename = "../PageArchive.zip";

    function __construct( ) {

        // Load zip library.
        error_reporting(E_ALL);
        if (!extension_loaded('zip')) {
            dl('zip.so');
        }
        $thisdir = dirname(__FILE__);

        // Create a new archive file.
        if( file_exists( $this->filename ) )
            unlink($this->filename);

        $this->zip = new ZipArchive();

        // Test
        if (!$this->zip->open($this->filename, ZIPARCHIVE::OVERWRITE)) {
            die("Error, unable to open {$this->filename}.  " .
                "Be sure Apache has permission " .
                "to write files in the /mod/folio/ folder.");
        } else {
            echo "Archive initialized OK<br/>";
        }

    }

    public function AddPage( folio_page $page ) {
        global $CFG;

        $view = new folio_BaseView();
        $view->Load( new folio_PageBodyView($page));
        $view->Load( new folio_PageAttachmentView( $page ));
        $html = $view->html();

        //$this->html .= $page->title . "<br/>";
        $user = folio_user::SelectWhereIdent( $page->user_ident );

        // Loop thru to find any links on the current site routing to
        //      the file_redirection.php file.
        $file_idents = array();
        $files = array();
        preg_match_all("/file_ident=[\d]+/i", $html, $file_idents );

        if( count($file_idents[0] > 0) )
            foreach( $file_idents[0] as $key => $ident )
                if( !isset( $files[substr( $ident, 11)]))
                    $files[substr( $ident, 11)] =
                            folio_file::SelectWhereIdent( substr( $ident, 11) );

        foreach( $files as $file ) {
            // Add to zip.
            $newpath = $this->AddFile( $file, $user );

            // Replace all instances with the new name.
            $html = str_replace( $CFG->wwwroot .
                              "mod/folio/html/file_redirection.php?file_ident=" .
                              $file->ident,
                              $newpath,
                              $html);
        }

        $this->zip->addFromString($user->username . '\\' . $page->title . ".html",
                          $html);
        echo "Page {$page->title} added OK<br/>\n";
    }

    /**
     * Add a file to the zip
     * @param string $path
     * @return string New Path
     */
    private function AddFile( folio_file $file, folio_user $user ) {
        global $CFG;
        $path =  'file/' . $file->ident . '/' . $file->originalname;

        if( !file_exists( $CFG->dataroot . $file->location ))
            trigger_error('Error, unable to find file "' .
                          $CFG->dataroot . $file->location . '"', E_USER_ERROR);

        // Add the username to the start of this path. Don't want to return it
        //      to the calling function though, as that name should be relative
        //      to the user
        $this->zip->addFile( $CFG->dataroot . $file->location,
                            $user->username . '/' . $path );

        echo "File {$file->originalname} added OK<br/>";

        return $path;
    }

    public function toString() {
        $this->zip->close();

echo "<br/><br/>File Archive created.  Please right-click and choose the 'save as' option " .
    "to download it to your computer.<br/><br/>";
echo '<a href="' . url . 'mod/folio/PageArchive.zip">Click to download archive</a>';

    }
}

?>
